# This workflow fails in PRs with changes to the review/api directory

name: 'Does PR have API changes?'
on:
  pull_request:

jobs:
  api-changes:
    runs-on: ubuntu-latest

    env:
      NODE_VERSION: '16.x'
      CACHE_PREFIX: '1'

    steps:
      - name: Checkout repo
        uses: actions/checkout@v4

      - name: Install node
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}

      # Cache yarn
      - name: Get yarn cache directory path
        id: yarn-cache-dir-path
        shell: bash
        run: echo "::set-output name=dir::$(yarn cache dir)"
      - name: Cache yarn
        uses: actions/cache@v4
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ env.CACHE_PREFIX }}-yarn-${{ env.NODE_VERSION }}-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ env.CACHE_PREFIX }}-yarn-${{ env.NODE_VERSION }}

      - name: Run api-extractor
        shell: bash
        run: |
          set -ex
          yarn
          yarn build
          yarn api

      - name: Dummy commit
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add ./review/api/*.api.md
          git commit --allow-empty -m "API changes"

      - name: Get API changes
        id: api-changed
        uses: tj-actions/changed-files@v42.0.5
        with:
          base_sha: 'HEAD~1'
          sha: 'HEAD'
          # only checks for modified files in this directory
          files: review/api/*.api.md

      - name: Fail if API are modified
        if: steps.api-changed.outputs.any_changed == 'true'
        run: |
          for file in ${{ steps.api-changed.outputs.all_changed_files }}; do
            echo "$file"
          done
          exit 1
